// 原使用@hapi/joi中间件，运行时报错joi版本混淆
const joi = require('joi')
const express = require('express')
const app = express()
const cors = require('cors')


app.use(cors())

app.use(express.urlencoded({extended: false}))

app.use((req, res, next) => {
    res.cc = (err, status = 1) => {
        res.send({
            status,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

const expressJwt = require('express-jwt')
const config = require('./config')
app.use(expressJwt({secret: config.jwtSecretKey}).unless({path: [/^\/api/]}))

const userRouter = require('./router/user')
app.use('/api', userRouter)

const userinfoRouter = require('./router/userinfo')
app.use('/my', userinfoRouter)

app.use((err, req, res, next) => {
    if(err instanceof joi.ValidationError) return res.cc(err)
    if(err.name === 'UnauthorizedError') return res.cc('身份认证失败！')
    res.cc(err)
})
app.listen(3007, ()=> {
    console.log('app running at http://127.0.0.1:3007')
})